package cc.eddic.practice.spring.webapi;


import cc.eddic.practice.spring.domain.SubCategory;
import cc.eddic.practice.spring.dto.CategoryAddRequest;
import cc.eddic.practice.spring.dto.CategoryResponse;
import cc.eddic.practice.spring.dto.SubCategoryAddRequest;
import cc.eddic.practice.spring.dto.SubCategoryResponse;
import cc.eddic.practice.spring.repository.CategoryRepository;


import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.transaction.Transactional;

import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("api/categories")
public class CategoryRestController {

    public CategoryRestController(CategoryRepository repository){this.categoryRepository= repository;}
    @PostMapping
    public HttpEntity<?> add(@RequestBody final CategoryAddRequest model){
        val category = categoryRepository.save(model.as());
        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(category.getId()).toUri()).build();
    }

    @GetMapping("/{id}")
    public HttpEntity<CategoryResponse> get(@PathVariable("id") final long id){
        if (log.isDebugEnabled()) log.debug("id = {}",id);
        val category = categoryRepository.findById(id).orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(CategoryResponse.from(category));
    }

    @Transactional
    @PostMapping("/{categoryId}/subcategories")
    public HttpEntity<?> add(@PathVariable("categoryId") Long categoryId, @RequestBody final SubCategoryAddRequest model){
        val category = categoryRepository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subCategory = model.as();
        category.add(subCategory);
        categoryRepository.save(category);

        val id = category.getSubCatogorires().stream()
                .filter(x -> x.getName().equals(model.getName()))
                .sorted(Comparator.comparing(SubCategory::getCreatedOn).reversed())
                .map(SubCategory::getId)
                .findFirst().orElse( -1L);


        if (log.isDebugEnabled()) {
            log.debug("sub category id {}",subCategory.getId());
            log.debug("(filter) sub category id {}",id);
        }


        return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().path("/{categoryId}/subcategories/{subCategoryId}").buildAndExpand(category.getId()).toUri()).build();
    }

    @GetMapping("/{categoryId}/subcategories")
    public HttpEntity<?> get(@PathVariable("categoryId") Long categoryId){
        if (log.isDebugEnabled()) log.debug("categoryId = {}",categoryId);
        val category = categoryRepository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        if (log.isDebugEnabled()) log.debug("run lazy load");
        return ResponseEntity.ok(category.getSubCatogorires().stream().map(SubCategoryResponse::from).collect(Collectors.toList()));
    }

    @GetMapping("/{categoryId}/subcategories/{subCategoryId}")
    public HttpEntity<?> get(@PathVariable("categoryId") Long categoryId,@PathVariable("subCategoryId") Long subCategoryId ){
        if (log.isDebugEnabled()) log.debug("categoryId = {},subCategoryId = {}",categoryId,subCategoryId);
        val category = categoryRepository.findById(categoryId).orElseThrow(NoSuchElementException::new);
        val subcategory = category.getSubCatogorires().stream().filter(subCategory -> subCategory.getId().equals(subCategoryId)).findFirst().orElseThrow(NoSuchElementException::new);
        return ResponseEntity.ok(SubCategoryResponse.from(subcategory));
    }

    final CategoryRepository categoryRepository;
}
